package com.bobamrz.frontend;

import java.io.IOException;
import java.security.InvalidParameterException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.bobamrz.service.AuthentificationService;

public class LoginServlet extends SuperServlet {

	private static final long serialVersionUID = -126870022651059091L;
	private Logger log = Logger.getLogger(LoginServlet.class);
	
	@Override
	protected void processPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String password = request.getParameter("password");
		String username = request.getParameter("username");
		processRequest(password, username, request, response);
	}
	
	@Override
	protected void processGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(null, null, request, response);
	}
	
	private void processRequest(String password, String username, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(password == null || username == null) {
			log.debug("no parameters - showing login page");
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/pages/login.jsp");
			dispatcher.forward(request, response);
			return;
		} 
		AuthentificationService authService = new AuthentificationService();
		boolean authentificationOk = authService.authentificate(username, password, request.getSession());
		if(authentificationOk) {
			log.debug("auth ok");
			//request.setAttribute("pageToLoad", "/WEB-INF/pages/docView.jsp");
			response.sendRedirect("documentView?catalog=1");
		} else {
			log.debug("auth failed");
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/pages/login.jsp");
			request.setAttribute("error", "Invalid username/password");
			dispatcher.forward(request, response);
		}
		
	}

}
